package pool

import (
	"fmt"
	"github.com/jinzhu/gorm"
	poolConstruct "github.com/silenceper/pool"
	"github.com/spf13/viper"
	"shortURL/pkg/db"
)

func initDbPool() error {
	Db = make(map[string]poolConstruct.Pool)

	for _, name := range viper.GetStringSlice("pool.initial_db_pool") {
		poolConfig := &poolConstruct.Config{
			InitialCap: viper.GetInt(fmt.Sprintf("db.%s.initialCap", name)), //资源池初始连接数
			MaxIdle:    viper.GetInt(fmt.Sprintf("db.%s.maxIdle", name)),    //最大空闲连接数
			MaxCap:     viper.GetInt(fmt.Sprintf("db.%s.maxCap", name)),     //最大并发连接数
			Factory: func() (interface{}, error) {
				return db.GetInstance(db.Options{
					UserName: viper.GetString(fmt.Sprintf("db.%s.username", name)),
					Password: viper.GetString(fmt.Sprintf("db.%s.password", name)),
					Addr:     viper.GetString(fmt.Sprintf("db.%s.addr", name)),
					Db:       viper.GetString(fmt.Sprintf("db.%s.name", name)),
					GormLog:  viper.GetBool("gormlog"),
				})
			},
			Close: func(v interface{}) error {
				return v.(*gorm.DB).Close()
			},
			//Ping: func(v interface{}) error{
			//	_, err := v.(*gorm.DB).Ping().Result()
			//	return err
			//},
			//连接最大空闲时间，超过该时间的连接 将会关闭，可避免空闲时连接EOF，自动失效的问题
			IdleTimeout: viper.GetDuration(fmt.Sprintf("db.%s.idleTimeout", name)),
		}

		p, err := poolConstruct.NewChannelPool(poolConfig)
		if err != nil {
			return err
		}

		Db[name] = p
	}

	return nil
}
